package com.qf.leadnewsuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.leadnewsmodel.dtos.ResponseResult;
import com.qf.leadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.leadnewsuser.mapper.ApUserMapper;
import com.qf.leadnewsuser.model.dtos.LoginDto;
import com.qf.leadnewsuser.model.pojos.ApUser;
import com.qf.leadnewsuser.service.ApUserService;
import com.qf.leadnewsutils.commons.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) throws NoSuchAlgorithmException {

        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();

        //判断phone不为null，长度不为0，数据不为空格 ”   “
        if (!StringUtils.isBlank(phone) && !StringUtils.isBlank(password)){
            //非游客模式
            LambdaQueryWrapper<ApUser> qw = new LambdaQueryWrapper<>();
            qw.eq(ApUser::getPhone,phone);
            ApUser apUser = getOne(qw);

            if (apUser == null){
                //号码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }else{
                //号码正确，比对密码
                String salt = apUser.getSalt();
                //将前台传递过来的原始密码和盐值拼接，共同计算md5值
                String md5s = DigestUtils.md5DigestAsHex((password+salt).getBytes(StandardCharsets.UTF_8));
                //将计算出来的md5和从数据库查询出来的密码进行比对
                String dbPwd = apUser.getPassword();
                if (dbPwd.equals(md5s)){
                    //登录成功 -- 返回jwt（基于用户的id生成）
                    String token = AppJwtUtil.getToken(apUser.getId());
                    Map map = new HashMap();
                    map.put("token",token);

                    //替换敏感信息(利用脱敏框架)
                    apUser.setSalt("");
                    apUser.setPassword("");
                    map.put("user",apUser);

                    return ResponseResult.okResult(map);
                }else{
                    //密码错误
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
                }
            }
        }else{
            //游客模式 -- 返回jwt（id设置0）
            String token = AppJwtUtil.getToken(0l);
            Map map = new HashMap();
            map.put("token",token);

            return ResponseResult.okResult(map);
        }
    }

}
